<template>
  <div class="login-wrapper">
    <el-row>
      <el-col :span="12" :offset="6">
        <el-card class="login-card">
          <el-form ref="loginForm" :model="loginForm" :rules="loginRules" label-width="80px">
            <h2 class="text-center">登录</h2>
            <el-form-item label="用户名" prop="username">
              <el-input v-model="loginForm.username" placeholder="请输入用户名"></el-input>
            </el-form-item>
            <el-form-item label="密码" prop="password">
              <el-input v-model="loginForm.password" placeholder="请输入密码" type="password"></el-input>
            </el-form-item>
            <el-form-item>
              <el-button type="primary" @click="login">登录</el-button>
            </el-form-item>
          </el-form>
          <div class="text-center">
            <router-link to="/register">没有账号？去注册</router-link>
          </div>
        </el-card>
      </el-col>
    </el-row>
  </div>
</template>

<script>
import axios from "@/request";

export default {
  name: "Login",
  data() {
    return {
      loginForm: {
        username: "",
        password: "",
      },
      loginRules: {
        username: [
          {required: true, message: "请输入用户名", trigger: "blur"},
        ],
        password: [
          {required: true, message: "请输入密码", trigger: "blur"},
        ],
      },
    };
  },
  methods: {
    login() {
      this.$refs.loginForm.validate(valid => {
        if (valid) {
          // 处理登录逻辑
          axios.post("/loginAndRegister/login", {
            username: this.loginForm.username,
            password: this.loginForm.password
          }).then((res) => {
            console.log(res)
            if (res.code === 200) {
              console.log(res.message);
              this.$message.success(res.message);
              localStorage.setItem("user", JSON.stringify(res.data))
              this.$router.push('/home')

            } else {
              console.error(res.message);
              this.$message.error(res.message);

            }
          })


          console.log("登录成功");
        } else {
          console.log("登录失败");
          return false;
        }
      });
    },
  },
};
</script>

<style scoped>
.login-wrapper {
  height: 100vh;
  display: flex;
  justify-content: center;
  align-items: center;
}

.login-card {
  width: 400px;
  margin-top: 50px;
  padding: 40px;
}

.text-center {
  text-align: center;
  margin-top: 20px;
}
</style>
